import { Component, OnInit } from '@angular/core';
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import {HttpClient,HttpHeaders,HttpErrorResponse} from "@angular/common/http";
import { ToastController } from '@ionic/angular';
import {environment} from 'src/environments/environment';
import { EncryptService } from '@services/encrypt.service';
import { AuthTokenService } from '@services/auth-token.service';
import { CommonResponse,CommonService,ToastColor,UpdateUserPasswordTypeEnum,VerificationType } from '@services/common-service.service';
import { DefaultLanguageService } from '@services/default-language.service';
import {TranslateService} from '@ngx-translate/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-input-password',
  templateUrl: './input-password.page.html',
  styleUrls: ['./input-password.page.scss'],
})
export class InputPasswordPage implements OnInit {

  public loading:boolean = false;

  public i18n:any;

  constructor(private router: Router,
    private route: ActivatedRoute,
    public http:HttpClient,
    private toastController: ToastController,
    private encryptService:EncryptService,
    private authTokenService:AuthTokenService,
    private commonService:CommonService,
    private defaultLanguageService:DefaultLanguageService,
    private translate:TranslateService) { 
      this.i18n = this.commonService.initTranslate(['auth.reset-pwd.input-password']); 
    }

  private appUserId:String;

  public validateForm:FormGroup;
  ngOnInit() {
    this.route.queryParams.subscribe((data)=>{
      this.appUserId = data.appUserId;
    })
    this.validateForm = new FormGroup({
      'password':new FormControl('', [
        Validators.required,
        Validators.pattern('(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}')
      ]),
      'repeatPassword':new FormControl('', [
        Validators.required,
        Validators.pattern('(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}')
      ])
    },{
      updateOn:'blur',
      validators: this.passwordMatchValidator
    });
  }

  signIn(){
    this.router.navigate(['/auth/signin-password']);
  }

  passwordMatchValidator(formGroup:FormGroup) {
    let newPassword = formGroup.get('password').value;
    let repeatPassword = formGroup.get('repeatPassword').value;
    if(!newPassword || !repeatPassword || (newPassword == repeatPassword)){
      return {};
    }
    return {'notMatch':true};
  }

  get password(){return this.validateForm.get('password');}
  get repeatPassword(){return this.validateForm.get('repeatPassword');}

  updatePassword(){
    if(this.validateForm.invalid){
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
      return false;
    }
    this.loading = true;
    let api = '/scm/app/updateUserPassword.do';
    let requestJson = {
      voUserApp:{
        appUserId:this.appUserId,
        password:this.encryptService.md5Ecrypt(this.validateForm.value.password)
      },
      updateUserPasswordType:UpdateUserPasswordTypeEnum.WITH_SMS_CODE,
      verificationType:VerificationType.UPDATE_USER_PASSWORD_BEFORE_LOGIN
    }
    let currentTime = new Date().getTime();
    let sign1 = this.encryptService.md5Ecrypt(this.authTokenService.getDeviceId()+currentTime);
    let sign2 = this.encryptService.rsaEcrypt(this.authTokenService.getDeviceId()+","+currentTime);
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json','sign1':sign1,'sign2':sign2 })
    };
    this.http.post(api,requestJson,httpOptions).subscribe((response:CommonResponse)=>{
      if(response.isSuccess){
        this.commonService.commonToast(ToastColor.success,this.i18n.update_success);
        let navigationExtras: NavigationExtras = {
          queryParams: {
            'appUserId':this.appUserId
          }
        };
        this.router.navigate(['/auth/signin-password'],navigationExtras);
      }else{
        this.commonService.commonToast(ToastColor.warning,this.i18n.update_failed);
      }
      this.loading = false;
    },(errorResponse:HttpErrorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
      this.loading = false;
    })
  }
}
